package com.gitee.slowcreator.http.config;

import cn.hutool.core.lang.Singleton;
import com.gitee.slowcreator.http.exception.SlowCreatorHttpException;
import com.gitee.slowcreator.http.executor.okhttp.OkhttpTimeoutInterceptor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
 * @author zxw
 * @date 2023/6/9 21:58
 */
@Slf4j
public class OkHttpConfig {

    /**
     * okhttp相关配置 如果未传入 则使用默认的配置
     * 如果传入了okHttpClient，请设置addInterceptor(new OkhttpTimeoutInterceptor()) 否则超时时间定制化的功能设置会失效
     */
    private static volatile OkHttpClient okHttpClient;

    /**
     * 获取okhttp client
     *
     * @return
     */
    public static OkHttpClient getOkHttpClient() {

        return Singleton.get("ok_http_client", () -> OkHttpConfig.setAndGetOkHttpClient(null));
    }

    /**
     * 获得并设置okhttp client
     *
     * @param okHttpClient 用户传入的okhttp client 如果为null 会使用默认参数初始化
     * @return 如果已存在okhttp client，则返回已存在的client 否则会初始化okhttp client
     */
    public static OkHttpClient setAndGetOkHttpClient(OkHttpClient okHttpClient) {

        if (OkHttpConfig.okHttpClient == null) {
            boolean setClientStatus = setOkHttpClient(okHttpClient);
            if (!setClientStatus) {
                log.warn("本次设置okhttp client 失败");
            }
        }

        return OkHttpConfig.okHttpClient;
    }

    /**
     * 设置okhttp client 如果不存在的话 存在的话不会设置
     *
     * @param okHttpClient 传入的okhttp client
     * @return 是否设置成功
     */
    private static boolean setOkHttpClient(OkHttpClient okHttpClient) {

        if (OkHttpConfig.okHttpClient == null) {
            synchronized (ScHttpConfig.class) {
                if (OkHttpConfig.okHttpClient == null) {
                    if (okHttpClient == null) {
                        okHttpClient = new OkHttpClient().newBuilder()
                                .addInterceptor(new OkhttpTimeoutInterceptor())
                                .sslSocketFactory(sslSocketFactory(), x509TrustManager())
                                .connectTimeout(5000, TimeUnit.MILLISECONDS)
                                .readTimeout(10000, TimeUnit.MILLISECONDS)
                                .writeTimeout(10000, TimeUnit.MILLISECONDS)
                                .build();
                    }

                    OkHttpConfig.okHttpClient = okHttpClient;
                    return true;
                }
            }
        }

        return false;
    }

    private static SSLSocketFactory sslSocketFactory() {
        try {
            // 信任任何链接
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            log.error("get socket factory error:", e);
            throw new SlowCreatorHttpException("获取socket factory 失败！");
        }
    }

    public static X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }
}
